package cn.cool.domain.activity.service.trial.node;

import cn.cool.domain.activity.model.entity.MarketProductEntity;
import cn.cool.domain.activity.model.entity.TrialBalanceEntity;
import cn.cool.domain.activity.model.valobj.GroupBuyActivityDiscountVO;
import cn.cool.domain.activity.model.valobj.SkuVO;
import cn.cool.domain.activity.service.discount.IDiscountCalculateService;
import cn.cool.domain.activity.service.trial.AbstractGroupBuyMarketSupport;
import cn.cool.domain.activity.service.trial.factory.DefaultActivityStrategyFactory;
import cn.cool.domain.activity.service.trial.thread.QueryGroupBuyActivityDiscountVOThreadTask;
import cn.cool.domain.activity.service.trial.thread.QuerySkuVOFromDBThreadTask;
import cn.cool.types.design.framework.tree.StrategyHandler;
import cn.cool.types.enums.ResponseCode;
import cn.cool.types.exception.AppException;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Map;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 营销节点，做一些功能的试算
 */
@Slf4j
@Service
public class MarketNode extends AbstractGroupBuyMarketSupport<MarketProductEntity, DefaultActivityStrategyFactory.DynamicContext, TrialBalanceEntity> {
    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Resource
    private ErrorNode errorNode;

    @Resource
    private TagNode tagNode;

    @Resource
    private Map<String, IDiscountCalculateService> discountCalculateServiceMap;

    @Override
    protected void multiThread(MarketProductEntity requestParameter, DefaultActivityStrategyFactory.DynamicContext dynamicContext) throws Exception {
        log.info("优惠试算 - 试算节点:多线程加载数据： requestParameter = {}, dynamicContext = {}", JSONUtil.toJsonStr(requestParameter), JSONUtil.toJsonStr(dynamicContext));
        // 加入多线程
        QueryGroupBuyActivityDiscountVOThreadTask queryGroupBuyActivityDiscountVOThreadTask = new QueryGroupBuyActivityDiscountVOThreadTask(requestParameter.getSource(), requestParameter.getChannel(), requestParameter.getGoodsId(), repository);

        FutureTask<GroupBuyActivityDiscountVO> groupBuyActivityDiscountVOFutureTask = new FutureTask<>(queryGroupBuyActivityDiscountVOThreadTask);
        threadPoolExecutor.execute(groupBuyActivityDiscountVOFutureTask);

        QuerySkuVOFromDBThreadTask querySkuVOFromDBThreadTask = new QuerySkuVOFromDBThreadTask(requestParameter.getGoodsId(), repository);
        FutureTask<SkuVO> skuVOFutureTask = new FutureTask<>(querySkuVOFromDBThreadTask);
        threadPoolExecutor.execute(skuVOFutureTask);

        dynamicContext.setGroupBuyActivityDiscountVO(groupBuyActivityDiscountVOFutureTask.get(timeout, TimeUnit.SECONDS));
        dynamicContext.setSkuVO(skuVOFutureTask.get(timeout, TimeUnit.SECONDS));
    }

    @Override
    public TrialBalanceEntity doApply(MarketProductEntity requestParameter, DefaultActivityStrategyFactory.DynamicContext dynamicContext) throws Exception {
        log.info("优惠试算 - 试算节点:核心业务逻辑： requestParameter = {}, dynamicContext = {}", JSONUtil.toJsonStr(requestParameter), JSONUtil.toJsonStr(dynamicContext));
        GroupBuyActivityDiscountVO groupBuyActivityDiscountVO = dynamicContext.getGroupBuyActivityDiscountVO();
        if (groupBuyActivityDiscountVO == null) {
            return router(requestParameter, dynamicContext);
        }
        GroupBuyActivityDiscountVO.GroupBuyDiscount groupBuyDiscount = groupBuyActivityDiscountVO.getGroupBuyDiscount();
        SkuVO skuVO = dynamicContext.getSkuVO();
        if (groupBuyDiscount == null || skuVO == null) {
            return router(requestParameter, dynamicContext);
        }

        IDiscountCalculateService discountCalculateService = discountCalculateServiceMap.get(groupBuyDiscount.getMarketPlan());
        if (discountCalculateService == null) {
            throw new AppException(ResponseCode.E0001.getCode(), ResponseCode.E0001.getInfo());
        }

        // 优惠价格 & 折扣金额
        BigDecimal payPrice = discountCalculateService.calculate(requestParameter.getUserId(), skuVO.getOriginalPrice(), groupBuyDiscount);
        dynamicContext.setDeductionPrice(skuVO.getOriginalPrice().subtract(payPrice));
        dynamicContext.setPayPrice(payPrice);

        return router(requestParameter, dynamicContext);
    }

    @Override
    public StrategyHandler<MarketProductEntity, DefaultActivityStrategyFactory.DynamicContext, TrialBalanceEntity> get(MarketProductEntity requestParameter, DefaultActivityStrategyFactory.DynamicContext dynamicContext) throws Exception {
        // 不存在配置的拼团活动，走异常节点
        if (null == dynamicContext.getGroupBuyActivityDiscountVO() || null == dynamicContext.getSkuVO() || null == dynamicContext.getDeductionPrice()) {
            return errorNode;
        }

        return tagNode;
    }

}
